<script setup lang="ts">
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { MenuApi } from '#/api/system/menu';
import type { SystemApi } from '#/api/system/system';

import { computed, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { IconifyIcon, Plus } from '@vben/icons';

import { ElButton, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteMenu, getMenuList } from '#/api/system/menu';
import { $t } from '#/locales';

import Form from './components/form.vue';
import { MenuTypeEnum, useGridColumns } from './data';

interface Props {
  systemData?: SystemApi.System;
}

const props = defineProps<Props>();

const emit = defineEmits(['close']);

const systemInfo = ref<SystemApi.System>();

const title = computed(() => {
  const systemName = systemInfo.value?.name || props.systemData?.name || '';
  return `菜单权限管理 - ${systemName}`;
});

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  destroyOnClose: true,
});

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 创建菜单 */
function onCreate() {
  const systemId = systemInfo.value?.id || props.systemData?.id;
  if (!systemId) {
    ElMessage.error('系统信息获取失败');
    return;
  }
  formDrawerApi.setData({ systemId }).open();
}

/** 添加下级菜单 */
function onAppend(row: MenuApi.Menu) {
  const systemId = systemInfo.value?.id || props.systemData?.id;
  if (!systemId) {
    ElMessage.error('系统信息获取失败');
    return;
  }

  // 根据父菜单类型设置默认菜单类型
  let defaultMenuType = 'M'; // 默认为目录
  if (row.menuType === 'M') {
    // 目录类型 -> 默认菜单类型为菜单
    defaultMenuType = 'C';
  } else if (row.menuType === 'C') {
    // 菜单类型 -> 默认菜单类型为按钮
    defaultMenuType = 'F';
  }

  formDrawerApi
    .setData({
      pid: row.id,
      systemId,
      menuType: defaultMenuType,
    })
    .open();
}

/** 编辑菜单 */
function onEdit(row: MenuApi.Menu) {
  formDrawerApi.setData(row).open();
}

/** 删除菜单 */
async function onDelete(row: MenuApi.Menu) {
  await ElMessageBox.confirm('确定要删除该菜单吗？', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  });
  await deleteMenu(row.id as number);
  ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.title]));
  onRefresh();
}

/** 表格操作按钮的回调函数 */
function onActionClick({ code, row }: OnActionClickParams<MenuApi.Menu>) {
  switch (code) {
    case 'append': {
      onAppend(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
  }
}

/** 切换树形展开/收缩状态 */
const isExpanded = ref(false);
function toggleExpand() {
  isExpanded.value = !isExpanded.value;
  gridApi.grid.setAllTreeExpand(isExpanded.value);
}

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useGridColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async (_params) => {
          const systemId = systemInfo.value?.id || props.systemData?.id;
          if (!systemId) {
            throw new Error('系统ID不能为空');
          }
          return await getMenuList(systemId);
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },
    toolbarConfig: {
    },
    treeConfig: {
      parentField: 'pid',
      rowField: 'id',
      transform: true,
      reserve: true,
    },
  } as VxeTableGridOptions,
});

// 获取抽屉API以便外部调用
const [Drawer, drawerApi] = useVbenDrawer({
  class: 'w-full max-w-none',
  appendToMain: true,
  destroyOnClose: true,
  async onConfirm() {
    // 绑定角色抽屉的确认操作 - 直接关闭抽屉
    await drawerApi.close();
  },
  onCancel() {
    emit('close');
    drawerApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      systemInfo.value = undefined;
      return;
    }
    // 从传入的数据中获取系统信息
    const data = drawerApi.getData<SystemApi.System>();
    if (data) {
      systemInfo.value = data;
    }
  },
});

// 暴露API供外部使用
defineExpose({
  drawerApi,
});
</script>

<template>
  <Drawer
    :title="title"
    :closable="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <FormDrawer @success="onRefresh" />
    <Grid table-title="菜单列表">
      <template #toolbar-tools>
        <ElButton
          type="primary"
          @click="onCreate"
          v-access:code="['system:system:menu:add']"
        >
          <Plus class="mr-2 size-5" />
          {{ $t('ui.actionTitle.create', ['菜单']) }}
        </ElButton>
        <ElButton class="ml-2" @click="toggleExpand">
          {{ isExpanded ? '收缩' : '展开' }}
        </ElButton>
      </template>
      <template #title="{ row }">
        <div class="flex w-full items-center gap-1">
          <div class="size-5 flex-shrink-0">
            <IconifyIcon
              v-if="row.menuType === MenuTypeEnum.BUTTON"
              icon="carbon:square-outline"
              class="size-full"
            />
            <IconifyIcon
              v-else-if="row.icon"
              :icon="row.icon || 'carbon:circle-dash'"
              class="size-full"
            />
          </div>
          <span class="flex-auto">{{ row.title }}</span>
          <div class="items-center justify-end"></div>
        </div>
      </template>
    </Grid>
  </Drawer>
</template>
